package com.cqupt.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cqupt.exception.BusinessException;
import com.cqupt.mapper.ArticleMapper;
import com.cqupt.model.pojo.Article;
import com.cqupt.model.pojo.UserArticle;
import com.cqupt.model.vo.ResultCodeEnum;
import com.cqupt.service.UserArticleService;
import com.cqupt.mapper.UserArticleMapper;
import com.cqupt.utils.AuthContextUtil;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;


@Service
public class UserArticleServiceImpl extends ServiceImpl<UserArticleMapper, UserArticle>
        implements UserArticleService {

    @Resource
    private ArticleMapper articleMapper;

    @Resource
    private UserArticleMapper userArticleMapper;

    @Override
    public void mark(int id) {
        Integer userId = AuthContextUtil.get().getId();
        Article article = articleMapper.selectById(id);
        UserArticle userArticle = new UserArticle();

        LambdaQueryWrapper<UserArticle> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserArticle::getUserId, userId);
        wrapper.eq(UserArticle::getArticleId, article.getId());
        UserArticle one = userArticleMapper.selectOne(wrapper);
        if (ObjectUtil.isNotNull(one)) {
            throw new BusinessException(ResultCodeEnum.DATA_ERROR);
        }
        userArticle.setUserId(userId);
        userArticle.setArticleId(article.getId());
        userArticle.setCategoryId(article.getCategoryId());
        userArticleMapper.insert(userArticle);
    }

    @Override
    public void unmark(int id) {
        Integer userId = AuthContextUtil.get().getId();
        LambdaQueryWrapper<UserArticle> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserArticle::getArticleId, id);
        wrapper.eq(UserArticle::getUserId, userId);
        userArticleMapper.delete(wrapper);
    }

    @Override
    public List<Article> getAllMarked() {
        Integer userId = AuthContextUtil.get().getId();
        return userArticleMapper.getAllMarked(userId);
    }

    @Override
    public List<Article> getMarkedByCategoryId(int categoryId) {
        Integer userId = AuthContextUtil.get().getId();
        return userArticleMapper.getMarkedByCategoryId(userId, categoryId);
    }
}




